package com.glela.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.glela.platform.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.serial.model.DiscoveryType;
import com.glela.serial.model.DiscoveryTypeFZVo;
import com.glela.serial.model.DiscoveryTypeVo;
import com.glela.serial.model.TitleDiscovery;
import com.glela.serial.model.TitleDiscoveryProduct;
import com.glela.serial.model.response.ResponseTitleDiscoveryVo;
import com.glela.serial.service.DiscoveryTypeService;
import com.glela.serial.service.TitleDiscoveryProductService;
import com.glela.serial.service.TitleDiscoveryService;

/**
 * @ClassName: DiscoveryController
 * @Description: 发现页面接口逻辑控制器
 * @author zhangrenjie
 * @date 2017年7月8日
 *
 */
@Controller
@RequestMapping("/discovery")
public class DiscoveryController extends BaseController {
	@Autowired
	private DiscoveryTypeService			discoveryTypeService;
	@Autowired
	private TitleDiscoveryService			titleDiscoveryService;
	@Autowired
	private TitleDiscoveryProductService	titleDiscoveryProductService;
	@Autowired
	private RedisUtil						redisUtil;
	@Autowired
	private BaseRestrictionsService			baseRestrictionsService;
	@Autowired
	private UserService						userService;

	/**
	 * @Title: queryAllDiscoveryType
	 * @Description: 发现首页初始化发现类型
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author zhangrenjie
	 * @date 2017年7月8日
	 */
	@RequestMapping("/queryDiscoveryType")
	public ResponseEntity<?> queryAllDiscoveryType() {
		try {
			List<DiscoveryType> list = discoveryTypeService.selectAllDiscoveryType();
			//			if (list.isEmpty()) {
			//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C24001),HttpStatus.OK);
			//			}
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("初始化发现类型接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * @Title: queryAllDiscoveryType
	 * @Description: 发现首页初始化发现类型(新版)
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author zhangrenjie
	 * @date 2017年11月27日
	 */
	@RequestMapping("/queryDiscoveryTypeNew")
	public ResponseEntity<?> queryAllDiscoveryTypeNew() {
		try {
			List<DiscoveryTypeFZVo> discoveryTypeFZVos = discoveryTypeService.selectAllDiscoveryTypeNew();
			return new ResponseEntity<>(new ResponseResultModel<>(discoveryTypeFZVos), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("初始化发现类型接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * @Title: queryAllDiscoveryByType
	 * @Description: 根据发现类型查询发现列表
	 * @param @param request
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author zhangrenjie
	 * @date 2017年7月8日
	 */
	@RequestMapping(value = "/selectAllDiscovery", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> queryAllDiscoveryByType(@RequestBody TitleDiscovery request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getType())) {//类型不能为空
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//			List<TitleDiscovery> list = this.titleDiscoveryService.selectDiscoveryPageByType(request);
			//			return new ResponseEntity<>(new ResponseResultModel<>(list),HttpStatus.OK);
			//加入redis缓存-------2017-11-01
			tempKey = getTempCacheKey(request.getType(), request.getStartIndex(), request.getPageSize());
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<TitleDiscovery> list = this.titleDiscoveryService.selectDiscoveryPageByType(request);
				rslt = toResultModelJSON(list);
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询发现列表接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return toRespEntity(toCacheResult(tempKey, rslt));
	}

	/**
	 * @Title: updateLikeTotalCountOfDiscovery
	 * @Description: 更新发现的喜欢人数
	 * @param flag 标记 1表示喜欢，0表示不喜欢
	 * @param id 发现的主键
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author zhangrenjie
	 * @date 2017年7月8日
	 */
	@RequestMapping(value = "/updateDiscovery", method = RequestMethod.POST)
	public ResponseEntity<?> updateLikeTotalCountOfDiscovery(@RequestBody Map<String, Integer> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (null == datas.get("flag")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if ((1 != datas.get("flag")) && (0 != datas.get("flag"))) {//校验标识
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C24005), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(datas.get("id"))) {//id不能为空
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int result = this.titleDiscoveryService.updateDiscovery(datas.get("id"), datas.get("flag"));
			if (0 == result) {//此发现不存在
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C24004), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("更新发现内容接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * @Title: queryAllDiscoveryProductByTitleId
	 * @Description: 根据发现查询发现商品列表（详情）
	 * @param @param request
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author zhangrenjie
	 * @date 2017年7月10日
	 */
	@RequestMapping(value = "/selectAllDiscoveryProduct", method = RequestMethod.POST)
	public ResponseEntity<?> queryAllDiscoveryProductByTitleId(@RequestBody TitleDiscoveryProduct request) {
		//	public ResponseEntity<?> queryAllDiscoveryProductByTitleId(@RequestBody Map<String ,Object> request){
		try {
			//			if (null == request || request.isEmpty()) {
			//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			//			}
			//			if (ParameterUtils.validParams(request.get("titleId"))) {//TitleId不能为空
			//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			//			}
			if (ParameterUtils.validParams(request.getTitleId())) {//TitleId不能为空
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<TitleDiscoveryProduct> list = this.titleDiscoveryProductService.selectAllDiscoveryProductByTitleId(request);
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("查询发现商品接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * @Title: queryAllDiscoveryMaterialListByType
	 * @Description: 查询发现素材列表
	 * @param @param request
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author zhangrenjie
	 * @date 2017年11月25日
	 */
	@RequestMapping(value = "/selectAllDiscoveryMaterialList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> queryAllDiscoveryMaterialListByType(@RequestBody TitleDiscovery request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getType())) {//类型不能为空
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//修改缓存的key
			String _login_user_store_flag = "XZJJ"; //登录店铺的标识，用来区分一般店铺和校妆姐姐店铺，XZJJ ： 为校妆姐姐
			Integer storeUserId = this.baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
			/*ResponseUser _login_user = null;//登录用户
			if (null != request.getUserId() && request.getUserId() > 0) {
				_login_user = this.userService.selectUserRoleById(request.getUserId());
				if (_login_user != null && StringUtils.isNotEmpty(_login_user.getRecommendFrom())) {
					String recommendFrom = _login_user.getRecommendFrom();//登录人对应的店主身份ID
					UserInfo userInfo = this.userService.selectUserInfoByPersionId(recommendFrom);//推荐人身份
					if (userInfo != null) {
						if (userInfo.getUserId() == (long) storeUserId) {
							_login_user_store_flag = "XZJJ";
						} else {
							_login_user_store_flag = "STORE";
						}
					} else {
						_login_user_store_flag = "XZJJ";
					}
				}
			}*/
			User _login_user = null;//登录用户
			if (null != request.getUserId() && request.getUserId() > 0) {
				_login_user = this.userService.getUserById(request.getUserId());
				if (_login_user != null && StringUtils.isNotEmpty(_login_user.getRecommendFrom())) {
					String recommendFrom = _login_user.getRecommendFrom();//登录人对应的店主身份ID
					User userInfo = this.userService.getUserByPersionId(recommendFrom);//推荐人身份
					if (userInfo != null) {
						if (userInfo.getId() != (long) storeUserId) {
							_login_user_store_flag = "STORE";
						}
					}
				}
			}
			tempKey = getTempCacheKey(request.getType(), _login_user_store_flag, request.getGoodId(), request.getStartIndex(), request.getPageSize());
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<ResponseTitleDiscoveryVo> list = this.titleDiscoveryService.selectDiscoveryMaterialListPageByType(request);
				rslt = toResultModelJSONNew(list);
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询发现素材列表接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return toRespEntity(toCacheResult(tempKey, rslt,60*2));
	}

	/**
	 * @Title: showRedDot
	 * @Description: 首页显示红点 返回每个类型最大数量 客户端判断是否显示红点
	 * @param id 发现的主键
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author wuyue
	 * @date 2017年11月25日
	 */
	@RequestMapping(value = "/showRedDot", method = RequestMethod.POST)
	public ResponseEntity<?> showRedDot() {
		String rslt = null;
		String tempKey = null;
		try {
			/*List<DiscoveryTypeVo> result = new ArrayList<>();
			String[] fields = { RedisKeys.FIELDS2, RedisKeys.FIELDS3, RedisKeys.FIELDS4 }; //2精选 3 资讯  4 素材
			String key = RedisKeys.YG_SYSTEM_TITLE_DISCOVERY;
			List<String> list = redisUtil.hmget(key, fields);
			// redis中未取到数据
			if (list.contains(null)) {
				result = this.titleDiscoveryService.findMaxIdsBytype();
			} else {
				// redis 中取到数据
				for (int i = 0; i < fields.length; i++) {
					DiscoveryTypeVo dis = new DiscoveryTypeVo();
					dis.setId(Integer.parseInt(list.get(i)));
					dis.setType(Integer.parseInt(fields[i]));
					result.add(dis);
				}
			}
			if (result.size() == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C24004), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
			*/
			//加入redis缓存30分钟
			tempKey = RedisKeys.YG_SYSTEM_TITLE_DISCOVERY;
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSONNew(this.titleDiscoveryService.findMaxIdsBytype());
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("发现表显示最大数量有异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return toRespEntity(toCacheResult(tempKey, rslt,60*30));
	}

	/**
	 * @Title: titleDiscoveryCount
	 * @Description: 更新分享或者保存次数
	 * @param titleDiscoveryId 发现表的主键
	 * @param type 1为分享 2 为保存 3为保存分享都有
	 * @param @return 参数
	 * @return ResponseEntity<?> 返回类型
	 * @throws @author wuyue
	 * @date 2017年11月27日
	 */
	@RequestMapping(value = "/titleDiscoveryCount", method = RequestMethod.POST)
	public ResponseEntity<?> titleDiscoveryCount(@RequestBody Map<String, Integer> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (null == datas.get("titleDiscoveryId") || null == datas.get("type")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if ((1 != datas.get("type")) && (2 != datas.get("type")) && (3 != datas.get("type"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C24005), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(datas.get("titleDiscoveryId")) || ParameterUtils.validParams(datas.get("type"))) {//id不能为空
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int result = this.titleDiscoveryService.updateDiscoveryCountByid(datas.get("titleDiscoveryId"), datas.get("type"));
			if (0 == result) {//此发现不存在
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C24004), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("更新分享保存发现接口计数异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
